import { ElMessage } from 'element-plus'
import type { Ref } from 'vue'
import type {
  EnergyDataReportInformant,
  ReportList,
} from '../types'

export default function useReportSave(
  lists: Ref<ReportList[]>,
  informant: EnergyDataReportInformant | Ref<EnergyDataReportInformant>,
  saveOrUpdate: (...arg: any[]) => Promise<any>,
  option?: {
    preProcessData?: (data: any[]) => void
    dataTime?: string
    getCalc?: (
      row: number,
      prop: string,
      value?: string | number | undefined
    ) => number | string | undefined
  },
) {
  const getData = () => {
    const lists2value = toValue(lists)
    const tempReg = /^temp_/
    /** 有效数据（ID存在或至少有一个字段值不为空） */
    const isNotEmpty = (v: any) =>
      !tempReg.test(v.uuid)
      || v.data.some((vv: any) => vv.value !== '')
    const dataTime = option?.dataTime || (`${new Date().getFullYear()}`)

    // 数据信息
    const data = lists2value.filter(isNotEmpty).map((v, i) => {
      const id = tempReg.test(String(v.uuid))
        ? undefined
        : +v.uuid
      return {
        id,
        type: 1,
        dataTime,
        ...v.data.reduce((acc, vv) => {
          acc[vv.key] = option?.getCalc
            ? option.getCalc(i, vv.key, vv.value) || ''
            : vv.value || ''
          return acc
        }, {} as any),
      }
    })

    // 填报人信息
    data.push({
      type: 2,
      dataTime,
      ...toValue(informant),
    })

    return data
  }

  async function saveStage() {
    const data = getData()
    option?.preProcessData?.(data)
    await saveOrUpdate(data)
    ElMessage.success('操作成功')
  }

  return {
    getData,
    /** 保存 */
    saveStage,
  }
}
